package com.tmall.testgen.transfer.client;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Map;

import com.tmall.testgen.common.ConnectionCommond;
import com.tmall.testgen.common.bo.interact.back.TransferCarFromClient;
import com.tmall.testgen.common.bo.interact.back.syn.AttatchJvmResult;
import com.tmall.testgen.common.bo.interact.back.syn.GetJvmListResult;
import com.tmall.testgen.common.socket.SocketInfoListener;
import com.tmall.testgen.common.socket.syn.SynCallBack;
import com.tmall.testgen.common.socket.syn.SynObject;

/**
 * @author haojia
 * @date 2014-07-04
 */
public class TransferClient {
	private static Socket socket;
	private static  OutputStream out;
	
	@SuppressWarnings("unchecked")
    public static  Map<String,String> getGvms(){
	    return   (Map<String, String>) new SynCallBack(){
            @Override
            public Object handleReceive(SynObject synObj) {
                
                if(synObj instanceof GetJvmListResult){
                    GetJvmListResult gj=(GetJvmListResult) synObj;
                    return gj.getJvmList();
                }
                
                return null;
            }
            
        }.sendObj(new TransferCarFromClient(TransferCarFromClient.TYPE_GET_JVM_LIST,null),out);
	}
	
	public static void closeSocket(){
	    try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	public static boolean isConnectedServer(){
	    return socket!=null&&!socket.isClosed()&&socket.isConnected();
	}
	
	public static   void startConnectServer(String serverIp) throws Exception {
	    
	    tryConn(serverIp);
		out =  socket.getOutputStream();
		new SocketInfoListener(socket,null,new TransferClientReceiveObjectHandler()).startListener();
		
		
	}
	

	/**
	 * 激活指定虚拟机 激活后中转服务器任务完成，关闭socket
	 * @param pid
	 */
	public static  void invokeVM(String pid){
	    
	    
	   new SynCallBack(){
            @Override
            public Object handleReceive(SynObject synObj) {
                
                if(synObj instanceof AttatchJvmResult){
                    try {
                        out.close();
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    System.out.println("客户端关闭socke");
                    return "succ";
                }
                
                return null;
            }
            
        }.sendObj(new TransferCarFromClient(TransferCarFromClient.TYPE_CONNECT_TO_ATTATCH,pid),out);
        
        
	}
	private static void tryConn(String ip) throws Exception{
	    
		try {
			socket = new Socket(ip, ConnectionCommond.Transfer_Server_Port);
		}catch(Exception e){
			Thread.sleep(1000);
			tryConn(ip);
		}
		
	}
}
